package com.example.blog2.web.admin;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.example.blog2.po.Result;
import com.example.blog2.po.StatusCode;
import org.joda.time.DateTime;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


@RestController
@CrossOrigin
public class PictureController {
    @PostMapping(value = "/upload")
    @ResponseBody
    public Result upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new Result(true, StatusCode.ERROR,"上传图片为空",null);
        }
        // 工具类获取值
        String endpoint = "oss-cn-shanghai.aliyuncs.com";
        String accessKeyId = "LTAI5tHoAg1kNd2fu4dFzK";
        String accessKeySecret = "eF0UmiWp2mgLIO1IkdQJCFbUqDk6";
        String bucketName = "gulimall-xudaWrZ9";

        try {
            // 创建OSS实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 上传文件流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String fileName  = file.getOriginalFilename();

            //在文件名称里面添加随机唯一的值
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            fileName = uuid + fileName;

            //把文件按日期进行分类
            // 2020/10/08/1.jpg
            //获取当前日期
            String datePath = new DateTime().toString("yyyy/MM/dd");
            //拼接
            fileName = datePath + "/" + fileName;

            //调用oss方法实现上传
            //第一个参数  Bucket名称
            //第二个参数  上传到oss文件路径和文件名称  aa/bb/1.jpg
            //第三个参数  上传文件输入流
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //把上传之后文件路径返回
            //需要把上传到阿里云oss路径手动拼接出来
            //   https://guli-edu-20201.oss-cn-beijing.aliyuncs.com/1.jpg

            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;
            Map<String,Object> info = new HashMap<>();
            info.put("data",url);
            //return url;
            return new Result(true, StatusCode.OK,"上传图片成功",info);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
